<?php
/**
* ShopEx licence
*
* @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
* @license  http://ecos.shopex.cn/ ShopEx License
 */

class b2c_ctl_site_gallery extends b2c_frontpage{

    var $_call = 'index';
    var $type='goodsCat';
    var $seoTag=array('shopname','search_numgoods_amount','goods_cat','goods_cat_p','goods_type','brand','sort_path');

    public function __construct(&$app) {
        parent::__construct($app);
        $shopname = app::get('site')->getConf('site.name');
        $this->shopname = $shopname;
        if ( isset($shopname) ) {
            $this->title = app::get('b2c')->_('商品分类').'_'.$shopname;
            $this->keywords = app::get('b2c')->_('商品分类_').'_'.$shopname;
            $this->description = app::get('b2c')->_('商品分类_').'_'.$shopname;
        }
        $this->_response->set_header('Cache-Control', 'no-store');
    }

    public function index($cat_id='',$urlFilter=null,$orderBy=0,$page=1,$virtual_cat_id=null,$showtype=null) {
        //商品详情页添加登录验证，by lsc 2018年10月30日09:58:21
        $this->verify_member();
        $this->pagedata['commentListListnum'] = $this->app->getConf('gallery.comment.time');
        $request_params = $this->_request->get_params();
        $urlFilter = utils::_filter_input($urlFilter);
        $urlFilter=htmlspecialchars(urldecode($urlFilter));
        $_GET['scontent'] = htmlspecialchars($_GET['scontent']);

        if(!empty($urlFilter) && $urlFilter != $_GET['scontent']){
            $urlFilter .= '_'.$_GET['scontent'];
        }else{
            $urlFilter = $_GET['scontent'];
        }
        if ( empty($cat_id) && empty($urlFilter) ) {
          $url = $this->gen_url(array('app'=>'site', 'ctl'=>'default', 'act'=>'index'));
          $this->_response->set_redirect($url)->send_headers();
        }
        $oSearch = $this->app->model('search');
	    $path = array();
        $system = '';
        $tmp_filter = $oSearch->decode($urlFilter,$path,$system);

        if($request_params[5] || $_GET['virtual_cat_id'] ){
            $virtual_cat_id = $request_params[5] ? $request_params[5] : intval($_GET['virtual_cat_id']);
        }
        $params = $this->filter_decode($tmp_filter,$cat_id,$virtual_cat_id);
  	    if(!empty($virtual_cat_id)){
            $v_filter=$this->_vcat_filter($virtual_cat_id,array());
            if(count($v_filter)){
                $params['filter'] = array_merge_recursive($params['filter'],$v_filter);
                $params['params']=array_merge_recursive($params['params'],$v_filter);
            }
        }
		$page = $params['page']?$params['page']:$page;
        $this->pagedata['filter'] = $params['params'];
        //默认按花型大小排序
        if(!$params['orderby']){
            $params['orderby'] = 'bn asc';
        }
        $goodsData = $this->get_goods($params['filter'],$page,$params['orderby'],$cat_id,$virtual_cat_id);

        //product_bn集合，方便前台批量获取库存，by liu，2017-1-4
        foreach ($goodsData as $good) {
            $this->pagedata['product_bns'][] = $good['products']['bn'];
        }
        $this->pagedata['product_bns'] = implode(',', $this->pagedata['product_bns']);
        // 前台销售价显示为相应会员价
        $userObject = kernel::single('b2c_user_object');
        $member_id = $userObject->get_member_session();
	    if($member_id){
            $memberLv = app::get('b2c')->model('members')->getList('member_lv_id',array('member_id'=>$member_id));
            $memberDiscout = app::get('b2c')->model('member_lv')->getList('member_lv_id,name,dis_count',array('member_lv_id'=>$memberLv[0]['member_lv_id']));
            // $goodsData[0]['price'] =$goodsData[0]['price'] * $memberDiscout[0]['dis_count'];
            foreach ($goodsData as $key => $value) {
                //2017-3-6 by jeff,增加会员价格处理,在普通会员和50元会员下测试正常，但是在特殊客户96折等级下显示有问题
                $_product_id = $value['products']['product_id'];
                $ocustomMPrice = app::get('b2c')->model('goods_lv_price')->getRow('*',array('product_id'=>$_product_id,'level_id'=>$memberLv[0]['member_lv_id']));
                if(count($ocustomMPrice)>0) {
                  $goodsData[$key]['price']=$ocustomMPrice['price'];
                  $goodsData[$key]['products']['price']=$ocustomMPrice['price'];
                } else {
                  $goodsData[$key]['price']=$goodsData[$key]['price'] * $memberDiscout[0]['dis_count'];
                  $goodsData[$key]['products']['price']=$goodsData[$key]['price'];
                }
            }
        }else{
            //未登录会员 库存显示为0. 2017/9/20 by 马国民
            //分类页所有商品未登录情况下全部不显示库存  价格显示为注册会员可见  2018-5-8  瓯堡于洁
            foreach ($goodsData as $key => &$val) {
                $val['NoShow']=true;
            }
            if($request_params[8]=='1'){
                $this->verify_member();
            }
        }
         //给商品附加预售信息
        $preparesell_is_actived = app::get('preparesell')->getConf('app_is_actived');
        if($preparesell_is_actived == 'true'){
            $prepare=app::get('preparesell')->model('preparesell_goods');
            foreach ($goodsData as $key => $value) {
                $prepare_goods = $prepare->getRow('*',array('product_id'=>$value['products']['product_id']));

                if(!empty($prepare_goods))
                {
                    $goodsData[$key]['prepare']=$prepare_goods;
                }
            }
        }
        //未登录的价格显示为0
        $userObject = kernel::single('b2c_user_object');
        $member_id = $userObject->get_member_id();
        if( empty($member_id) ){
            $this->pagedata['login'] = 'nologin';
        }
        $screen = $this->screen($cat_id,$params['params']);
        //对扩展属性进行自定义排序 产品系列放到最上面
        //$frist = array();
        // dump($screen['screen']['props']);exit;
        foreach ($screen['screen']['props'] as $k => &$vvv) {
            if($vvv['name']=='产品系列'){
                //$frist = $vvv;
                unset($screen['screen']['props'][$k]);
            }
        }
        //array_unshift($screen['screen']['props'],$frist);
        $this->pagedata['screen'] = $screen['screen'];
        $this->pagedata['active_filter'] = $screen['active_filter'];
        $this->pagedata['orderby_sql'] = $params['orderby'];
        $this->pagedata['showtype'] = $params['showtype'];
        $this->pagedata['is_store'] = $params['is_store'];

        if ($_COOKIE['LANG'] == 'en_US') {
            foreach ($goodsData as $key => $value) {
                include ROOT_DIR.'/config/unit.php';
                $goodsData[$key]['unit'] = $unit[$goodsData[$key]['unit']];
            }
        }
        $this->pagedata['goodsData'] = $goodsData;
        $this->pagedata['gallery_display_tag_goods'] = $this->app->getConf('gallery.display.tag.goods');

        #商品列表页中打开商品详情页方式
        $this->pagedata['opentype'] = $this->app->getConf('gallery.open_type');
        if($tmp_filter['search_keywords'][0]){
            $tmp_filter['search_keywords'][0] = str_replace('%xia%','_',$tmp_filter['search_keywords'][0]);
        }
        //面包屑
        $GLOBALS['runtime']['path'] = $this->runtime_path($cat_id,$tmp_filter['search_keywords'],$virtual_cat_id);
        //搜索关键字
        if(isset($tmp_filter['search_keywords'][0])){
            $keywords = str_replace(' ','%20',$tmp_filter['search_keywords'][0]);
            $this->set_cookie('S[SEARCH_KEY]',$keywords);
        }
        //setSeo
        $this->_set_seo($screen['seo_info']);
        //设置模板
        if( $this->goods_cat_setting['gallery_template'] ){
            $this->set_tmpl_file($this->goods_cat_setting['gallery_template']);                 //添加模板
        }
        //无价格模式：2019年10月14日17:02:00
        if ($_COOKIE['NOPRICE']==1) {
            $this->pagedata['NOPRICE'] = 1;
        }
        $this->set_tmpl('gallery');
        $this->page('site/gallery/index.html');
    }

    /*
     * 面包屑数据设置
     *
     * @params int $cat_id 分类ID
     * */
    private function runtime_path($cat_id,$search_keywords,$virtual_cat_id){
        //set 面包屑
        $global_runtime_path = "";
        if($search_keywords){//搜索的时候
            $GLOBALS['runtime']['search_key'] = $search_keywords;
            $newSearch_keywords = '';
            foreach ($search_keywords as $value) {
                $newSearch_keywords .=$value.',';
            }
            $keywords = trim($newSearch_keywords,',');
            $keywords = app::get('b2c')->_('搜索').'"'.$keywords.'"';
            $url = app::get('site')->router()->gen_url(array('app'=>'b2c','ctl'=>'site_gallery','act'=>'index')).'?scontent=n,'.$search_keywords;
            $global_runtime_path = array(
                array('type'=>'goodsCat','title'=>app::get('site')->_('首页'),'link'=>kernel::base_url(1)),
                array('type'=>'goodsCat','title'=>$keywords,'link'=>$url),
            );
            if($cat_id){
                $global_runtime_path[] = array('type'=>'goodsCat','title'=>$this->goods_cat,'link'=>kernel::base_url(1));
            }
        }elseif($virtual_cat_id){//虚拟分类的时候
            $virtualCat = app::get('b2c')->model('goods_virtual_cat')->getList('virtual_cat_name,url',array('virtual_cat_id'=>intval($virtual_cat_id)));
            $global_runtime_path = array(
                array('type'=>'goodsCat','title'=>app::get('site')->_('首页'),'link'=>kernel::base_url(1)),
                array('type'=>'goodsCat','title'=>$virtualCat[0]['virtual_cat_name'],'link'=>$virtualCat[0]['url']),
            );
            if($cat_id){
                $global_runtime_path[] = array('type'=>'goodsCat','title'=>$this->goods_cat,'link'=>kernel::base_url(1));
            }
        }else{
            $catModel = $this->app->model('goods_cat');
            if($cat_id && !cachemgr::get('global_runtime_path' . $cat_id, $global_runtime_path)){
                cachemgr::co_start();
                $global_runtime_path = $catModel->getPath($cat_id,'');
                cachemgr::set('global_runtime_path', $global_runtime_path, cachemgr::co_end());
            }
        }
        return $global_runtime_path;
    }

    /*
     * 设置列表页SEO
     *
     * @params array $seo_info
     * */
    private function _set_seo($seo_info){
        if(!empty($seo_info['seo_title']) || !empty($seo_info['seo_keywords']) || !empty($seo_info['seo_description'])){
            $this->title = $seo_info['seo_title'];
            $this->keywords = $seo_info['seo_keywords'];
            $this->description = $seo_info['seo_description'];
        }else{
            $this->setSeo('site_gallery','index',$this->prepareSeoData($this->pagedata));
        }
    }

    /*
     * 返回seo设置的数据
     *
     * */
    private function prepareSeoData($data){
        $catpath = $GLOBALS['runtime']['path'];
        if(is_array($catpath)){
            $cat_path = $catpath[0]['title'];
            unset($catpath[0]);
            foreach($catpath as $ck=>$cv){
                $cat_path .= ','.$cv['title'];
            }
        }
        return array(
            'shop_name'=>$this->shopname,
            'search_num'=>$data['total'],
            'goods_cat'=>$this->goods_cat?$this->goods_cat:'',
            'goods_cat_p'=>$cat_path,
            'goods_type'=>$this->goods_type ? $this->goods_type:'',
        );
    }

    /*
     * 根据分类ID提供筛选条件，并且返回已选择的条件数据
     *
     * @params int $cat_id 分类ID
     * @params array $filter 已选择的条件
     * */
    private function screen($cat_id,$filter){
        $screen['cat_id'] = $cat_id;
        $cat_id = $cat_id ?  $cat_id : $this->pagedata['show_cat_id'];
        //搜索时的分类
        if(!$screen['cat_id'] && count($this->pagedata['catArr']) > 1){
            // $searchCat = app::get('b2c')->model('goods_cat')->getList('cat_id,cat_name',array('cat_id'=>$this->pagedata['catArr']));
            // $i=0;
            // foreach($this->catCount as $catid=>$num){
            //     $sort[$catid] = $i;
            //     // if($i == 9) break;
            //     $i++;
            // }
            // foreach($searchCat as $row){
            //     $screen['search_cat'][$sort[$row['cat_id']]] = $row;
            // }
            // ksort($screen['search_cat']);
        }

        //商品子分类:这里需要判断虚拟分类的情况：若是虚拟分类则显示虚拟分类的子类；
        $show_cat = $this->app->getConf('site.cat.select');
        if($show_cat == 'true' && !$filter['virtual_cat_id']){ //表示：若不是虚拟分类
            $sCatData = app::get('b2c')->model('goods_cat')->getList('cat_id,cat_name',array('parent_id'=>$cat_id));
            $screen['cat'] = $sCatData;
        }else{
            $sCatData = app::get('b2c')->model('goods_virtual_cat')->getList('virtual_cat_id,virtual_cat_name,url',array('parent_id'=>$filter['virtual_cat_id']));
            $screen['virtual_cat'] = $sCatData;
        }
        cachemgr::co_start();
        if(!cachemgr::get("goodsObjectCat".$cat_id, $catInfo)){
            $goodsInfoCat = app::get("b2c")->model("goods_cat")->getList('*',array('cat_id'=>$cat_id) );
            $catInfo = $goodsInfoCat[0];
            cachemgr::set("goodsObjectCat".$cat_id, $catInfo, cachemgr::co_end());
        }
        $this->goods_cat = $catInfo['cat_name'];//seo
        $this->goods_cat_setting = $catInfo['gallery_setting'];//template
        cachemgr::co_start();
        if(!cachemgr::get("goodsObjectType".$catInfo['type_id'], $typeInfo)){
            $typeInfo = app::get("b2c")->model("goods_type")->dump2(array('type_id'=>$catInfo['type_id']) );
            cachemgr::set("goodsObjectType".$catInfo['type_id'], $typeInfo, cachemgr::co_end());
        }
        $this->goods_type = $typeInfo['name'];//seo
        if($typeInfo['price'] && $filter['price'][0]){
            $active_filter['price']['title'] = $this->app->_('价格');
            $active_filter['price']['label'] = 'price';
            $active_filter['price']['options'][0]['data'] =  $filter['price'][0];
            foreach($typeInfo['price'] as $key=>$price){
                $price_filter = implode('~',$price);
                if($filter['price'][0] == $price_filter){
                    $typeInfo['price'][$key]['active'] = 'active';
                    $active_arr['price'] = 'active';
                }
                $active_filter['price']['options'][0]['name'] = $filter['price'][0];
            }
        }
        $screen['price'] = $typeInfo['price'];

        if ( $typeInfo['setting']['use_brand'] ){
            $type_brand = app::get('b2c')->model('type_brand')->getList('brand_id',array('type_id'=>$catInfo['type_id']));
            if ( $type_brand ) {
                foreach ( $type_brand as $brand_k=>$brand_row ) {
                    $brand_ids[$brand_k] = $brand_row['brand_id'];
                }
            }
            $brands = app::get('b2c')->model('brand')->getList('brand_id,brand_name',array('brand_id'=>$brand_ids,'disabled'=>'false'));
            //是否已选择
            foreach($brands as $b_k=>$row){
  	        // 在用in_array前验证$filter['brand_id']是否是数组
            if( is_array($filter['brand_id']) && in_array($row['brand_id'],$filter['brand_id']) ){
                    $brands[$b_k]['active'] = 'active';
                    $active_arr['brand'] = 'active';
                    $active_filter['brand']['title'] = $this->app->_('品牌');;
                    $active_filter['brand']['label'] = 'brand_id';
                    $active_filter['brand']['options'][$row['brand_id']]['data'] =  $row['brand_id'];
                    $active_filter['brand']['options'][$row['brand_id']]['name'] = $row['brand_name'];
                }
            }
            $screen['brand'] = $brands;
        }

        //扩展属性
        if ( $typeInfo['setting']['use_props'] && $typeInfo['props'] ){
            foreach ( $typeInfo['props'] as $p_k => $p_v){
                if ( $p_v['search'] != 'disabled' ) {
                    $props[$p_k]['name'] = $p_v['name'];
                    $props[$p_k]['goods_p'] = $p_v['goods_p'];
                    $props[$p_k]['type'] = $p_v['type'];
                    $props[$p_k]['search'] = $p_v['search'];
                    $props[$p_k]['show'] = $p_v['show'];
                    $propsActive = array();
                    if($p_v['options']){
                        foreach($p_v['options'] as $propItemKey=>$propItemValue){
                            $activeKey = 'p_'.$p_v['goods_p'];
                            if($filter[$activeKey] && in_array($propItemKey,$filter[$activeKey])){
                                $active_filter[$activeKey]['title'] = $p_v['name'];
                                $active_filter[$activeKey]['label'] = $activeKey;
                                $active_filter[$activeKey]['options'][$propItemKey]['data'] =  $propItemKey;
                                $active_filter[$activeKey]['options'][$propItemKey]['name'] = $propItemValue;
                                $propsActive[$propItemKey] = 'active';
                            }
                        }
                    }
                    $props[$p_k]['options'] = $p_v['options'];
                    $props[$p_k]['active'] = $propsActive;
                }
            }

            $screen['props'] = $props;
        }

        //规格
        $gType = $this->app->model('goods_type');
        $SpecList = $gType->getSpec($catInfo['type_id'],1);//获取关联的规格
        if($SpecList){
            foreach($SpecList as $speck=>$spec_value){
                if($spec_value['spec_value']){
                    foreach($spec_value['spec_value'] as $specKey=>$SpecValue){
                        $activeKey = 's_'.$speck;
                        if($filter[$activeKey] && in_array($specKey,$filter[$activeKey])){
                            $active_filter[$activeKey]['title'] = $spec_value['name'];
                            $active_filter[$activeKey]['label'] = $activeKey;
                            $active_filter[$activeKey]['options'][$specKey]['data'] =  $specKey;
                            $active_filter[$activeKey]['options'][$specKey]['name'] = $SpecValue['spec_value'];
                            $specActive[$specKey] = 'active';
                        }
                    }
                }
                $SpecList[$speck]['active'] = $specActive;
            }
        }
        //暂时注释掉 2016年4月26日12:42:02
        // $screen['spec'] = $SpecList;

        //排序
        $orderBy = $this->app->model('goods')->orderBy();
        $screen['orderBy'] = $orderBy;
        /*//标签
        $tagFilter['app_id'][] = 'b2c';
        $giftAppActive = app::get('gift')->is_actived();
        if($giftAppActive){
            $tagFilter['app_id'][] = 'gift';
        }
        // $progetcouponAppActive的值是个布尔值，当作数组赋值回报错。貌似这个地方没什么用
        $progetcouponAppActive = app::get('progetcoupon')->is_actived();
        if($progetcouponAppActive){
	    $progetcouponAppActive = array();
            $progetcouponAppActive['app_id'][] = 'progetcoupon';
        }
        $tags = app::get('desktop')->model('tag')->getList('*',$tagFilter);
        if($filter['pTag']){
            $active_arr['pTags'] = 'active';
        }
        foreach($tags as $tag_key=>$tag_row){
            if($tag_row['tag_type'] == 'goods'){//商品标签
                // 在用in_array前验证$filter['gTag']是否时数组
                if(is_array($filter['gTag']) && in_array($tag_row['tag_id'],$filter['gTag'])){
                    $screen['tags']['goods'][$tag_key]['active'] = 'checked';
                }
                $screen['tags']['goods'][$tag_key]['tag_id'] = $tag_row['tag_id'];
                $screen['tags']['goods'][$tag_key]['tag_name'] = $tag_row['tag_name'];
            }elseif($tag_row['tag_type'] == 'promotion'){//促销标签
                // 在用in_array前验证$filter['pTag']是否时数组
                if(is_array($filter['pTag']) && in_array($tag_row['tag_id'],$filter['pTag'])){
                    $screen['tags']['promotion'][$tag_key]['active'] = 'active';
                    $active_filter['pTag']['title'] = $this->app->_('促销商品');;
                    $active_filter['pTag']['label'] = 'pTag';
                    $active_filter['pTag']['options'][$tag_row['tag_id']]['data'] =  $tag_row['tag_id'];
                    $active_filter['pTag']['options'][$tag_row['tag_id']]['name'] = $tag_row['tag_name'];
                }
                $screen['tags']['promotion'][$tag_key]['tag_id'] = $tag_row['tag_id'];
                $screen['tags']['promotion'][$tag_key]['tag_name'] = $tag_row['tag_name'];
            }
        }*/
        $this->pagedata['active_arr'] = $active_arr;
        $return['screen'] = $screen;
        $return['active_filter'] = $active_filter;
        $return['seo_info'] = $catInfo['seo_info'];
        // dump($return);die;
        return $return;
    }

    /*
     * 前台筛选商品ajax调用
     * */
    public function ajax_get_goods(){
        $_POST['cat_id'] = utils::_RemoveXSS($_POST['cat_id']);
        $_POST['virtual_cat_id'] = utils::_RemoveXSS($_POST['virtual_cat_id']);
	    $_POST['orderBy'] = utils::_RemoveXSS($_POST['orderBy']);
        $tmp_params = $this->filter_decode($_POST,$_POST['cat_id'],$_POST['virtual_cat_id']);

        $params = $tmp_params['filter'];
        $orderby = $tmp_params['orderby'];
        $showtype = $tmp_params['showtype'];
        $page = $tmp_params['page'] ? $tmp_params['page'] : 1;
        $goodsData = $this->get_goods($params,$page,$orderby,$_POST['cat_id'],$_POST['virtual_cat_id']);
        if($goodsData){
            if ($_COOKIE['LANG'] == 'en_US') {
                foreach ($goodsData as $key => $value) {
                    include ROOT_DIR.'/config/unit.php';
                    $goodsData[$key]['unit'] = $unit[$goodsData[$key]['unit']];
                }
            }
            //无价格模式：2019年10月14日17:02:00
            if ($_COOKIE['NOPRICE']==1) {
                $this->pagedata['NOPRICE'] = 1;
            }
            $this->pagedata['goodsData'] = $goodsData;
            $this->pagedata['gallery_display_tag_goods'] = $this->app->getConf('gallery.display.tag.goods');
            $this->pagedata['opentype'] = $this->app->getConf('gallery.open_type');
            $view = 'site/gallery/type/'.$showtype.'.html';
            echo $this->fetch($view);
        }else{
            //后台站点设置搜索为空页面
            echo app::get('site')->getConf('errorpage.search');
        }
    }

    /*
     * 返回搜索条件
     *
     * @params array $params 已有条件
     * @params int   $cat_id 分类ID
     * @params nit   $virtual_cat_id 虚拟分类ID
     * @return array
     */
    public function filter_decode($params=null,$cat_id,$virtual_cat_id=null){
        //如果params中某一个key没有相应的value，则去掉params中的这一项，这样在查看更多商品时，params会是一个空数组，就可以使用cookie中的筛选项了。by liu，2017-1-12
        foreach ($params as $key => $value) {
            if(!$value){
                unset($params[$key]);
            }
        }
        //获取cookie中的条件
        //如果是从搜索关键词进来的，则判断搜索关键词和cookie中是否相同，若不同则将cookie中的筛选条件清空，by liu，2017-1-12
        if($params['search_keywords'][0]){
            if($params['search_keywords'][0] == $_COOKIE['S']['SEARCH_KEY']){
                $cookie_filter = $_COOKIE['S']['GALLERY']['FILTER'];
                if($cookie_filter){
                    $tmp_params = explode('&',$cookie_filter);
                    foreach($tmp_params as $k=>$v){
                        if ($v) {
                            $arrfilter = explode('=',$v);
                            $f_k = str_replace('[]','',$arrfilter[0]);
                            if(in_array($f_k, array('cat_id','orderBy','showtype','is_store','page','pricea','pricez'))){
                                $params[$f_k] = $arrfilter[1];
                            }else{
                                $params[$f_k][] = $arrfilter[1];
                            }
                        }
                    }
                }
            }
            else{
                $this->set_cookie('S[GALLERY][FILTER]','nofilter');
            }
        }elseif(!$params){
            $cookie_filter = $_COOKIE['S']['GALLERY']['FILTER'];
            if($cookie_filter){
                $tmp_params = explode('&',$cookie_filter);
                foreach($tmp_params as $k=>$v){
                    if ($v) {
                        $arrfilter = explode('=',$v);
                        $f_k = str_replace('[]','',$arrfilter[0]);
                        if(in_array($f_k, array('cat_id','orderBy','showtype','is_store','page','pricea','pricez'))){
                            $params[$f_k] = $arrfilter[1];
                        }else{
                            $params[$f_k][] = $arrfilter[1];
                        }
                    }
                }
            }
            if($params['cat_id'] != $cat_id){
                unset($params);
                $this->set_cookie('S[GALLERY][FILTER]','nofilter');
            }
            if ($virtual_cat_id != ($params['virtual_cat_id'][0])) {
                unset($params);
            }
        }
        if($virtual_cat_id){
            $params['virtual_cat_id']  = $virtual_cat_id;
        }
        $filter['params'] = $params;
        #分类
        $params['cat_id'] = $cat_id ? $cat_id : $params['cat_id'];

        if(!$params['cat_id']) unset($params['cat_id']);

        if($params['search_keywords'][0]){
            $params['orderBy'] = $params['orderBy'] ? $params['orderBy'] : 'bn asc';
        }elseif($params['scontent']){
            $oSearch = $this->app->model('search');
            $decode = $oSearch->decode($params['scontent']);
            $params['search_keywords'] = $decode['search_keywords'];
            unset($params['scontent']);
        }

        if($params['search_keywords']){
            $params['search_keywords']= str_replace('%xia%','_',$params['search_keywords']);
        }

        #排序
        $orderby = $params['orderBy'];unset($params['orderBy']);

        #分页,页码
        $page= $params['page'];unset($params['page']);

        #商品显示方式
        if($params['showtype']){
            $showtype = $params['showtype'];unset($params['showtype']);
        }else{
            $showtype = app::get('b2c')->getConf('gallery.default_view');
        }

        $params['marketable'] = 'true';
        $params['is_buildexcerpts'] = 'true';
        $tmp_filter = $params;

        #价格区间筛选
        if($tmp_filter['price']){
            $tmp_filter['price'] = explode('~',$tmp_filter['price'][0]);
        }
        #商品标签筛选条件
        if($tmp_filter['gTag']){
            $tmp_filter['tag'] = $tmp_filter['gTag'];unset($tmp_filter['gTag']);
        }

        if($tmp_filter['is_store'] == 'on' || app::get('b2c')->getConf('gallery.display.stock_goods') != 'true'){
            #是否有货
            $is_store = $params['is_store'];
        }
        if($tmp_filter['virtual_cat_id']){
            $tmp_filter = $this->_merge_vcat_filter($tmp_filter['virtual_cat_id'],$tmp_filter);//合并虚拟分类条件
        }
        if($tmp_filter['pTag']){//促销优惠
            $time = time();
            $pTagGoods = app::get('b2c')->model('goods_promotion_ref')->getList('goods_id,apply_platform',array('tag_id'=>$tmp_filter['pTag'],'from_time|sthan'=>$time, 'to_time|bthan'=>$time,'status'=>'true'));
            if($pTagGoods){
                foreach($pTagGoods as $gids){
                    if(strpos($gids['apply_platform'],'1') === false){
                        continue;
                    }
                    $tmp_filter['goods_id'][] = $gids['goods_id'];
                }
            }
            if(empty($tmp_filter['goods_id']) ){
                $tmp_filter['goods_id'] = array(-1);
            }
            unset($tmp_filter['pTag']);
        }

        $filter['filter'] = $tmp_filter;
        $filter['orderby'] = $orderby;
        $filter['showtype'] = $showtype;
        $filter['is_store'] = $is_store;
        $filter['page'] = $page;
        return $filter;
    }

    /*
     * 将列表页中的搜索条件和虚拟分类条件合并
     *
     * @params int $virtual_cat_id 虚拟分类ID
     * @params array $filter  列表页搜索条件
     * */
    private function _merge_vcat_filter($virtual_cat_id,$filter){
        $virCatObj = $this->app->model('goods_virtual_cat');
        /** 颗粒缓存商品虚拟分类 **/
        if(!cachemgr::get('goods_virtual_cat_'.intval($virtual_cat_id), $vcat)){
            cachemgr::co_start();
            $vcat = $virCatObj->getList('cat_id,parent_id,cat_path,virtual_cat_id,filter,virtual_cat_name as cat_name',array('virtual_cat_id'=>intval($virtual_cat_id)));
            cachemgr::set('goods_virtual_cat_'.intval($virtual_cat_id), $vcat, cachemgr::co_end());
        }
        foreach ($vcat as $key => $value) {
            //如果是虚拟分类的一级分类，则查询其子类
            if ($value['parent_id'] ==0) {
                $isFirstCat =1;
                $vcat_sub = $virCatObj->getList('cat_id,parent_id,cat_path,virtual_cat_id,filter,virtual_cat_name as cat_name',array('parent_id'=>intval($virtual_cat_id)));
                $newFlag = array();
                $newStr = '';
                foreach ($vcat_sub as $ke => $val) {
                    $newStr.=$val['filter'].'&';
                    // parse_str($val['filter'],$flag);//把查询字符串解析到变量中
                    // array_push($newFlag, $flag);
                }
                $newStr.=$value['filter'];//合并一级类目的筛选项
                parse_str($newStr,$vcatFilters_new);//把查询字符串解析到变量中
            }
        }
        if ($isFirstCat) {
            $vcatFilters = $vcatFilters_new;
        }else{
            // $vcat = current( $vcat );current和foreach冲突？？
            $vcat = $vcat[0];
            parse_str($vcat['filter'],$vcatFilters);//把查询字符串解析到变量中
        }
        if($filter['cat_id'] && $vcatFilters['cat_id']){
            unset($vcatFilters['cat_id']);
        }
        $filter = array_merge_recursive($filter,$vcatFilters);
        return $filter;
    }

    private function _vcat_filter($virtual_cat_id){
        $v_filter=$this->_merge_vcat_filter($virtual_cat_id,array());
        $vcat_filter=array();
        if(count($v_filter['props'])){
            foreach($v_filter['props'] as $k => $val ){
                if(count($val) && $val['0'] != '_ANY_'){
                    $vcat_filter['p_'.$k] =$val;
                }
            }
        }
        return $vcat_filter;
    }
     /* 根据条件返回搜索到的商品
     * @params array $filter 搜索条件
     * @params int   $page   页码
     * @params string $orderby 排序
     * @return array
     * */
    public function get_goods($filter,$page=1,$orderby,$cat_id,$virtual_cat_id){
        $goodsObject = kernel::single('b2c_goods_object');
        $goodsModel = app::get('b2c')->model('goods');
        $productsModel = app::get('b2c')->model('products');
        $userObject = kernel::single('b2c_user_object');
        $member_id = $userObject->get_member_id();
        if( empty($member_id) ){
            $this->pagedata['login'] = 'nologin';
        }

        $page = $page ? $page : 1;
        $pageLimit = $this->app->getConf('gallery.display.listnum');
        $pageLimit = ($pageLimit ? $pageLimit : 20);
        $this->pagedata['pageLimit'] = $pageLimit;
        $total = false;
        //2015-10-16 by jiang 获取该用户是否有查看发样类的权限
        $userObject = kernel::single('b2c_user_object');
        $member_id = $userObject->get_member_session();
        $sql="select * from sdb_b2c_members where member_id='{$member_id}' and isfayang='1'";
        $rowMember = kernel::database()->select($sql);
        if(count($rowMember)==0){
            //获得产品扩展属性名为 是否为开发样
            // $sql = "select x.goods_p,y.props_value_id from sdb_b2c_goods_type_props x
            //         left join sdb_b2c_goods_type_props_value y on x.props_id=y.props_id
            //          where 1 and x.name='是否为开发样' and y.name='是'";
            // $rows = kernel::database()->select($sql);
            // if(count($rows)>0){
            //     $goods_p='p_'.$rows[0]['goods_p'];
            //     $filter['filter_sql'] = " ifnull(".$goods_p.",0)<>".$rows[0]['props_value_id']." ";
            // }

            $filter['isDeveloping']='false';
        }

        $x_filter =''; //定义一个条件判断是否是虚拟分类
        //筛选显示有货
        if ($filter['is_store']) {
            $filter['jxc_store|than'] =0;
        }
        if ($filter['pricea'] || $filter['pricez']) {
            $priceMin = $filter['pricea'] ? $filter['pricea'] : 1;
            $priceMax = $filter['pricez'] ? $filter['pricez'] : 1;
            if ($priceMin>$priceMax) {
                $priceTemp = $priceMin;
                $priceMin = $priceMax;
                $priceMax = $priceTemp;
            }
            $filter['price|between'] = array($priceMin,$priceMax);
        }
        $goodsData = $goodsModel->getList('*',$filter,$pageLimit*($page-1),$pageLimit,$orderby,$total=false);
        // 列表页库存调用jxc库存  2017-6-6 by ma
        foreach ($goodsData as $k => $v) {
            $procodes=$v['products']['bn'];
            if(strpos($procodes,'-yp')!==false){
                $bn=explode('-yp',$procodes);
                $procode=$bn[0];
            }else{
                $procode=$v['bn'];
            }
            $post = array(
                        'method'=>'Cangku.getKucun',
                        'params'=>array(
                            'product_id'=>$procode,
                            'kuweiName'=>'样品'
                        )
                    );
            $erp_caller_obj = kernel::service('apioubao.rpc_erp_request');
            $result = $erp_caller_obj->call_api_oubao($post);
            $result = json_decode($result,true);
            $result['data']['cnt'] = number_format($result['data']['cnt'],2);
            $goodsData[$k]['jxc_store'] = $result['data']['cnt'];
        }
        //获得需要置顶的商品id
        $topDatas = app::get('b2c')->getConf('gallery.top.itemid');
        $topDatas = explode(';', $topDatas);
        //此分类下有需要置顶的商品id
        $topItemId = 0;
        foreach ($topDatas as $key => $value) {
            if ($value) {
                $flag = explode('-', $value);
                if ($cat_id==$flag[0]) {
                    $topItemId = $flag[1];
                    break;
                }elseif ($virtual_cat_id == $flag[0]) {
                    $topItemId = $flag[1];
                    break;
                }
            }
        }
        if ($topItemId) {
            //置顶的商品信息：
            $topGoods = $goodsModel->getRow('*',array('goods_id'=>$topItemId));
            //判断当前页是否包含置顶的商品
            $haveTopGoods = false;
            foreach ($goodsData as $key1 => $value1) {
                if ($value1['goods_id'] == $topItemId) {
                    $haveTopGoods = true;
                    break;
                }
            }
            //置顶的商品放在第一页:当第一页不含置顶商品时
            if ($page==1 && !$haveTopGoods) {
                //先得到此页数据中最后一个元素。
                $deletGoods = end($goodsData);
                //删除数组最后一个元素
                array_pop($goodsData);
                //将置顶的商品加入到数组头部；
                array_unshift($goodsData, $topGoods);
            }elseif ($page==1 && $haveTopGoods) {//当第一页含置顶商品时
                //先得到此页数据中最后一个元素。
                $deletGoods = end($goodsData);
                //数组的数量
                $countGoodsData = count($goodsData);
                foreach ($goodsData as $key1 => $value1) {
                    //如果当前页数据中包含已经置顶的商品，删除置顶的商品，然后把已删除的商品$deletGoods添加到数组；
                    if ($value1['goods_id'] == $topItemId) {
                        unset($goodsData[$key1]);
                        $goodsData[$countGoodsData-1] = $deletGoods;
                        break;
                    }
                }
                //将置顶的商品加入到数组头部；
                array_unshift($goodsData, $topGoods);
            }elseif ($page !=1) {//当不是第一页
                //先获得前一页的最后一个数据
                $newGoodsData = $goodsModel->getList('*',$filter,$pageLimit*($page-1-1),$pageLimit,$orderby,$total=false);
                $deletGoods = end($newGoodsData);
                //删除数组最后一个元素
                array_pop($goodsData);
                //将前一页的最后一个商品加入到数组头部；
                array_unshift($goodsData, $deletGoods);
                if ($haveTopGoods) {//当不是第一页，含置顶商品时:前一页最后的商品放到当前页第一个,并删除置顶的商品
                    foreach ($goodsData as $key1 => $value1) {
                        if ($value1['goods_id'] == $topItemId) {
                            unset($goodsData[$key1]);
                            break;
                        }
                    }
                }
            }
        }
        foreach ($filter['props'] as &$v) {
            if($v[0]!= '_ANY_' ){
                $x_filter = 0;
            }
        }
        if($filter['props']==''){
            if($goodsData && $total ===false){
                $x_filter = 1;
            }
        }
        //不知道判断是否是虚拟分类有什么用 影响到虚拟分类的分页 故先注释掉
        //2016年6月7日16:07:20 by shen

        // if($x_filter == 0){
        //     $total = count($goodsData);
        // }else{
        //     $total = $goodsModel->count($filter);
        // }

        $total = $goodsModel->count($filter);

        $this->pagedata['total'] =  $total;
        $pagetotal= $this->pagedata['total'] ? ceil($this->pagedata['total']/$pageLimit) : 1;
        $max_pagetotal = $this->app->getConf('gallery.display.pagenum');
        $max_pagetotal = $max_pagetotal ? $max_pagetotal : 100;
        $this->pagedata['pagetotal'] = $pagetotal > $max_pagetotal ? $max_pagetotal : $pagetotal;
        $this->pagedata['page'] = $page;
        //分页
        $this->pagedata['pager'] = array(
            'current'=>$page,
            'total'=>$this->pagedata['pagetotal'],
            'link' =>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_gallery','act'=>'ajax_get_goods')),
        );
        $gfav = explode(',',$_COOKIE['S']['GFAV'][$member_id]);
        foreach($goodsData as $key=>$goods_row){
            if(in_array($goods_row['goods_id'],$gfav)){
                $goodsData[$key]['is_fav'] = 'true';
            }
            if($goods_row['udfimg'] == 'true' && $goods_row['thumbnail_pic']){
                $goodsData[$key]['image_default_id'] = $goods_row['thumbnail_pic'];
            }
            $gids[$key] = $goods_row['goods_id'];
            //判断是否多个规格，若是单规格方便在列表页直接加入购物车
            if (count( current($goods_row['spec_desc']) ) >1) {
                $goodsData[$key]['fastbuy'] = 0;
            }else{
                $goodsData[$key]['fastbuy'] = 1;
            }
        }

        if($filter['search_keywords'] || $filter['virtual_cat_id']){
            if(kernel::service('server.search_type.b2c_goods') && $searchrule = searchrule_search::instance('b2c_goods') ){
                if($searchrule){
                    $catCount = $searchrule->get_cat($filter);
                }
            }else{
                $sfilter = 'select cat_id,count(cat_id) as count from sdb_b2c_goods WHERE ';
                $sfilter .= $goodsModel->_filter($filter);
                $sfilter .= ' group by cat_id';
                $sfilter .= ' having cat_id >0';
                $cats = $goodsModel->db->select($sfilter);
                if($cats){
                    foreach($cats as $cat_row){
                        $catCount[$cat_row['cat_id']] = $cat_row['count'];
                    }
                }
            }
        }
        //搜索时的分类
        if(!empty($catCount) && count($catCount) != 1){
            arsort($catCount);
            $this->pagedata['show_cat_id'] = key($catCount);
            $this->pagedata['catArr'] = array_keys($catCount);
            $this->catCount = $catCount;
        }else{
            $this->pagedata['show_cat_id'] = key($catCount);
        }

        //货品
        $goodsData = $this->get_product($gids,$goodsData);

        //促销标签
        $goodsData = $this->get_goods_promotion($gids,$goodsData);

        //商品标签信息
        foreach( kernel::servicelist('tags_special.add') as $services ) {
            if ( is_object($services)) {
                if ( method_exists( $services, 'add') ) {
                    $services->add( $gids, $goodsData);
                }
            }
        }
        $goodsData = $this->get_goods_point($gids,$goodsData);
        //给商品附加预售信息
        $preparesell_is_actived = app::get('preparesell')->getConf('app_is_actived');
        if($preparesell_is_actived == 'true'){
            $prepare=app::get('preparesell')->model('preparesell_goods');
            foreach ($goodsData as $key => $value) {
                $prepare_goods = $prepare->getRow('*',array('product_id'=>$value['products']['product_id']));
                if(!empty($prepare_goods))
                {
                    $goodsData[$key]['prepare']=$prepare_goods;
                }
            }
        }
        return $goodsData;
    }

    /*
     * 获取搜索到的商品的默认货品数据，并且格式化货品数据(货品市场价，库存等)
     *
     * @params array $gids 搜索到到的商品ID集合
     * @params array $goodsData 搜索到的商品数据
     * @return array
     * */
    private function get_product($gids,$goodsData){
        $this->pagedata['imageDefault'] = app::get('image')->getConf('image.set');
        $productModel = $this->app->model('products');
        $products =  $productModel->getList('*',array('goods_id'=>$gids,'is_default'=>'true','marketable'=>'true'));
        $show_mark_price = $this->app->getConf('site.show_mark_price');

        #检测货品是否参与special活动
        if($object_price = kernel::service('sepcial_goods_check')){
            $object_price->check_special_goods_list($products);
        }

        $sdf_product = array();
        foreach($products as $key=>$row){
            $sdf_product[$row['goods_id']] = $row;
        }
        foreach ($goodsData as $gk=>$goods_row){
            $product_row = $sdf_product[$goods_row['goods_id']];
            $goodsData[$gk]['products'] = $product_row;
            //市场价
            if($show_mark_price =='true'){
                if($product_row['mktprice'] == '' || $product_row['mktprice'] == null)
                    $goodsData[$gk]['products']['mktprice'] = $productModel->getRealMkt($product_row['price']);
            }

            //库存
            if($goods_row['nostore_sell'] || $product_row['store'] === null){
                $goodsData[$gk]['products']['store'] = 999999;
            }else{
                $store = $product_row['store'] - $product_row['freez'];
                $goodsData[$gk]['products']['store'] = $store > 0 ? $store : 0;
            }

            //2015-10-15 by jiang 未登录 价格显示0
            $userObject = kernel::single('b2c_user_object');
            $member_id = $userObject->get_member_session();
            if(!$member_id){
                $goodsData[$gk]['products']['mktprice']=0;
                $goodsData[$gk]['products']['price']=0;
                $goodsData[$gk]['products']['store']='0';
                $goodsData[$gk]['jxc_store']='0';
            }
        }
        return $goodsData;
    }

    /*
     * 获取搜索到的商品的促销信息
     *
     * @params array $gids 搜索到到的商品ID集合
     * @params array $goodsData 搜索到的商品数据
     * @return array
     * */
    private function get_goods_promotion($gids,$goodsData){
        //商品促销
        $time = time();
        $order = kernel::single('b2c_cart_prefilter_promotion_goods')->order();
        $goodsPromotion = app::get('b2c')->model('goods_promotion_ref')->getList('*', array('goods_id'=>$gids, 'from_time|sthan'=>$time, 'to_time|bthan'=>$time,'status'=>'true'),0,-1,$order);
        if($goodsPromotion){
            $black_gid = array();
            foreach($goodsPromotion as $row) {
                if(in_array($row['goods_id'],$black_gid)) continue;
                if(strpos($row['apply_platform'],'1') === false){
                    continue;
                }
                $tags[] = $row['tag_id'];
                $promotionData[$row['goods_id']][] = $row['tag_id'];
                if( $row['stop_rules_processing']=='true' ){
                    $black_gid[] = $row['goods_id'];
                }
            }
        }
        $tagModel = app::get('desktop')->model('tag');
        $sdf_tags = $tagModel->getList('tag_id,tag_name',array('tag_id'=>$tags));
        foreach($sdf_tags  as $tag_row){
            $tagsData[$tag_row['tag_id']] = $tag_row;
        }
        foreach($promotionData as $gid=>$p_row){
            foreach($p_row as $k=>$tag_id){
                $promotion_tags[$gid][$k] = $tagsData[$tag_id];
            }
        }
        foreach($goodsData as $key=>$goods_row){
			if($goods_row['products']['promotion_type']){
				continue;
			}
            $goodsData[$key]['promotion_tags'] = $promotion_tags[$goods_row['goods_id']];
        }
        return $goodsData;
    }

    /*
     * 获取搜索到的商品的积分信息
     *
     * @params array $gids 搜索到到的商品ID集合
     * @params array $goodsData 搜索到的商品数据
     * @return array
     * */
    private function get_goods_point($gids,$goodsData){
        $pointModel = $this->app->model('comment_goods_point');
        $goods_point_status = app::get('b2c')->getConf('goods.point.status');
        $this->pagedata['point_status'] = $goods_point_status ? $goods_point_status: 'on';
        if($this->pagedata['point_status'] == 'on'){
            $sdf_point = $pointModel->get_single_point_arr($gids);
            foreach($goodsData as $key=>$row){
                $goodsData[$key]['goods_point'] = $sdf_point[$row['goods_id']];
                #$goodsData[$key]['comments_count'] = $sdf_point[$row['goods_id']]['comments_count'];
            }
        }
        return $goodsData;
    }

    /*
     * 商品对比(前台对比调用)
     * */
    public function diff(){
        $this->_response->set_header('Cache-Control', 'no-store');
        $imageDefault = app::get('image')->getConf('image.set');

        $goodsModel = $this->app->model('goods');
        $productModel = $this->app->model('products');
        $member_id = kernel::single('b2c_user_object')->get_member_id();
        if(!$member_id){
            $this->pagedata['login'] = 'nologin';
        }

        if($_POST['goods_id']){
            foreach($_POST['goods_id'] as $k=>$goods_id){
                $gid[$k]=intval($goods_id);
            }
        }else{
            echo '没有对比商品';exit;
        }

        if(empty($_POST['type_id'])){
            echo '参数错误';exit;
        }
        $goodsType = kernel::single('b2c_goods_object')->get_goods_type(null,$_POST);
        $goodsData = $goodsModel->getList('*',array('goods_id'=>$gid,'marketable'=>'true') );
        $objPoint = $this->app->model('comment_goods_point');
        $goods_point_status = app::get('b2c')->getConf('goods.point.status');
        $this->pagedata['point_status'] = $goods_point_status ? $goods_point_status: 'on';
        if($goodsData){
            foreach($goodsData as $key=>$goods_row){
                $brand_id[] = $goods_row['brand_id'];
                $goodsparams[$key]['params'] = $goods_row['params'];
                $goodsBasicInfo[$key]['goods_id'] = $goods_row['goods_id'];
                $goodsBasicInfo[$key]['name'] = $goods_row['name'];
                $goodsBasicInfo[$key]['image_default_id'] = $goods_row['image_default_id'];
                $arrProps = kernel::single('b2c_goods_object')->get_goods_type_info($goodsType['props'],$goods_row);
                $goodsProps[$key]['props'] = $arrProps;
                $products = $productModel->getList('weight,price,product_id,spec_info,store,freez',array('goods_id'=>$goods_row['goods_id']));

                if($object_price = kernel::service('sepcial_goods_check')){
                    $object_price->check_special_goods_list($products);
                }

                $goodsPrice[$key]['price'] = $products[0]['price'];
                $goodsBasicInfo[$key]['product_id'] = $products[0]['product_id'];
                $goodsBasicInfo[$key]['spec_info'] = $products[0]['spec_info'];
                $goodsBasicInfo[$key]['store'] = ($products[0]['nostore_sell'] || is_null($products[0]['store']) ) ? 999999 : ($products[0]['store'] - $products[0]['freez']);
                $goodsBrind[$key]['brand_id'] = $goods_row['brand_id'];
                $goodsWeight[$key]['weight'] = $products[0]['weight'];
                /**** start 商品评分 ****/
                $goodsPoint[$key]['goods_point'] = $objPoint->get_single_point($goods_row['goods_id']);
                $goodsPoint[$key]['point_num'] = $goods_row['comments_count'];
                $goodsPoint[$key]['product_id'] = $products[0]['product_id'];
                /**** end 商品评分 ****/
            }
            $brand_data = app::get('b2c')->model('brand')->getList('brand_id,brand_name',array('brand_id'=>$brand_id));
            foreach($brand_data as $brand_row){
                $brandInfo[$brand_row['brand_id']] = $brand_row['brand_name'];
            }
        }
        //加入商品对比的详细参数
        foreach($goodsparams as $key=>$val){
            if(empty($val['params']))
            {
                $format_goodsparams[$key]['params']=null;
            }
            foreach ($val['params'] as $para => $param) {

                foreach ($param as $group => $row) {
                    $format_goodsparams[$key]['params'][$group]['name']=$group;
                    $format_goodsparams[$key]['params'][$group]['value']=$row;
                    $format_goodsparams_type[$group]=$group;
                }
            }
        }
        $this->pagedata['goodsBasicInfo'] = $goodsBasicInfo;
        $this->pagedata['goods_params'] = $format_goodsparams;
        $this->pagedata['goods_params_type'] = $format_goodsparams_type;
        $this->pagedata['goodsProps'] = $goodsProps;
        $this->pagedata['goodsType'] = $goodsType['props'];
        $this->pagedata['goodsPrice'] = $goodsPrice;
        $this->pagedata['goodsWeight'] = $goodsWeight;
        $this->pagedata['goodsPoint'] = $goodsPoint;
        $this->pagedata['goodsBrind'] = $goodsBrind;
        $this->pagedata['brand'] = $brandInfo;
        $this->page('site/gallery/compare.html');
   }

   /**
    * ps ：ajax获取商品库存
    * Time：2017/01/04 16:01:53
    * @author liuxin
    * @param 参数类型
    * @return 返回值类型
   */
    public function ajax_products_store(){
        $product_bn = $_POST['id'];
        $product_bn = explode(',', $product_bn);
        $_model_product = app::get('b2c')->model('products');

        $userObject = kernel::single('b2c_user_object');
        $member_id = $userObject->get_member_id();
        if( empty($member_id) ){
            echo json_encode(array('success'=>false,'data'=>null));exit();
        }
        $product_bns = array();
        foreach ($product_bn as $bn) {
            $_bn = $_model_product->getBnJxc($bn);
            $product_bns[] = "'{$_bn['bn']}'";
        }
        if($product_bns){
            $product_bns = implode( ',', $product_bns);
            $post = array(
                'method'=>'Cangku.getproductsKucun',
                'params'=>array(
                    'product_id'=>$product_bns,
                )
            );

            $erp_caller_obj = kernel::service('apioubao.rpc_erp_request');
            $result = $erp_caller_obj->call_api_oubao($post);
            $result = json_decode($result,true);
            foreach ($result['data'] as $data) {
                $store[] = array(
                    'productId' => $data['productId'].'-xh',
                    'cnt' => round($data['cnt'],2),
                );
            }
        }
        echo json_encode(array('success'=>true,'data'=>$store));exit();
    }
    /**
       * ps ：优惠券领取
       * Time：2017年1月11日 20:31:37
       * @author shen
       */
    public function coupon_receive(){
        if( isset($_POST['cpns_id']) ){
            $cpnsId = $_POST['cpns_id'];

            $concurrent_cpns=kernel::single("base_concurrent_file");
            $cpns_group_id = 'cpns_group_'.intval($cpnsId%1000);
            $concurrent_cpns->status($cpns_group_id);
            if(!$concurrent_cpns->check_flock()){
                $concurrent_cpns->close_lock();
                echo json_encode(array('status'=>'fail',msg=>"网络异常，请重试"));exit();
            }
            $oExchangeCoupon = kernel::single('b2c_coupon_mem');
            // $memberId = intval($this->app->member_id);//会员id号
            $userObject = kernel::single('b2c_user_object');
            // $siteMember = $userObject->get_current_member();
            $siteMember = $userObject->get_member_id();
            $memberId= $siteMember;
            $obj_widget_coupons = kernel::single('b2c_widgets_coupons');
            if($memberId){
                $msgArr = array(
                    '2'=>'cpns_id为空',
                    '3'=>'优惠券已经领光',
                    '4'=>'会员等级不符',
                    '5'=>'活动未开始',
                    '6'=>'活动已结束',
                );

                $verify_status = $obj_widget_coupons->verify($cpnsId);
                if( $verify_status != 1 ){
                    $concurrent_cpns->close_lock();
                    echo json_encode(array('status'=>'fail',msg=>$msgArr[$verify_status]));exit();
                }
                $receive_status = $obj_widget_coupons->getReceiveStatus($cpnsId);
                if( $receive_status ){
                    $concurrent_cpns->close_lock();
                    if( $receive_status != 2){
                        echo json_encode(array('status'=>'fail',msg=>'不可重复领取'));exit();
                    }else{
                        echo json_encode(array('status'=>'fail',msg=>$msgArr[$receive_status]));exit();
                    }

                }
                $coupons = $this->app->model('coupons');
                $cur_coupon = $coupons->dump($cpnsId);

                if( $oExchangeCoupon->obtain($cpnsId,$memberId,$params) ){
                    $concurrent_cpns->unlock();
                    echo json_encode(array('status'=>'success',msg=>"领取成功"));exit();
                }else
                {
                    $concurrent_cpns->close_lock();
                    echo json_encode(array('status'=>'fail',msg=>"领取失败"));exit();
                }
            }else{
                $concurrent_cpns->close_lock();
                $url = $this->gen_url(array('app'=>'b2c', 'ctl'=>'site_passport','act'=>'login','full'=>1));
                echo json_encode(array('status'=>'fail',msg=>"还未登录,无法领取优惠券！",'url'=>$url));exit();
            }
        }

        echo json_encode(array('status'=>'fail',msg=>"参数异常"));exit();
    }
}
